package synchronicity.agent;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Vector;

import synchronicity.calendar.Calendar.ModifyCalendarFailedException;
import synchronicity.host.SchedulerHost;
import synchronicity.util.Range;

/**
 * An Agent that can request a meeting to be scheduled on each
 * host. Also keeps track of which hosts accepted and which hosts
 * declined.
 */
public class SchedulerAgent extends Agent {
	public static final String TYPE = "SchedulerAgent";

	private Range meetingTime;

	private String title;

	private Vector failedHosts, successfulHosts;

	public SchedulerAgent(Range meetingTime, String title) {
		this.meetingTime = meetingTime;
		this.title = title;
		failedHosts = new Vector();
		successfulHosts = new Vector();
	}

	protected void visitHost(SchedulerHost host) {
		try {
			host.addMeeting(meetingTime, title);
			successfulHosts.addElement(host.getHostIdentifier());
		} catch (ModifyCalendarFailedException e) {
			failedHosts.addElement(host.getHostIdentifier());
		}
	}

	protected void readAgent(DataInputStream stream) throws IOException {
		failedHosts.removeAllElements();
		successfulHosts.removeAllElements();
		meetingTime = new Range(0, 0);
		
		meetingTime.read(stream);
		title = stream.readUTF();

		int failedLength = stream.readInt();
		for(int ii = 0; ii <failedLength; ii++){
			String hostName = stream.readUTF();
			failedHosts.addElement(hostName);
		}
		int succeededLength = stream.readInt();
		for(int ii = 0; ii <succeededLength; ii++){
			String hostName = stream.readUTF();
			successfulHosts.addElement(hostName);
		}
	}

	protected void writeAgent(DataOutputStream stream) throws IOException {
		meetingTime.write(stream);
		stream.writeUTF(title);
		
		stream.writeInt(failedHosts.size());
		for(int ii =0 ;ii < failedHosts.size();ii++) {
			stream.writeUTF((String)failedHosts.elementAt(ii));
		}
		stream.writeInt(successfulHosts.size() );
		for(int ii = 0; ii < successfulHosts.size();ii++){
			stream.writeUTF((String)successfulHosts.elementAt(ii));
		}
	}
	
	public String getType() {
		return TYPE;
	}

	public Vector getFailedHosts() {
		return failedHosts;
	}

	public Range getMeetingTime() {
		return meetingTime;
	}

	public Vector getSuccessfulHosts() {
		return successfulHosts;
	}

	public String getTitle() {
		return title;
	}
}
